package com.example.c94s3plyhyfc.biz;

import com.example.c94s3plyhyfc.bean.Bbs;
import com.example.c94s3plyhyfc.mapper.BbsMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Errors;

import javax.annotation.Resource;
import javax.validation.Valid;

@Service
// 事务注解一般添加在业务层
@Transactional(rollbackFor = BizException.class)
public class BbsBiz {

    @Resource
    private BbsMapper bm;

    public void save(@Valid Bbs bbs, Errors errors) throws BizException {
        if (errors.hasErrors()) {
            throw new BizException("字段验证错误!", errors.getAllErrors());
        }
        // 同名验证: 用户注册
        Bbs b = new Bbs();
        b.setTitle(bbs.getTitle());
        int cnt = bm.countByObj(b);
        if (cnt > 0) {
            errors.rejectValue("title", "ValueError","标题同名");
            throw new BizException("标题同名", errors.getAllErrors());
        }
        bm.insert(bbs);
    }


}
